package dao;

import entity.Address;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import utils.DateUtils;
import utils.DbUtils;

import java.sql.SQLException;
import java.util.List;

/**
 * @author lishunlin110
 * @version 1.0
 * @description: 地址数据交互层实现
 * @date 2021/10/16 16:00
 */
public class AddressDaoImpl implements AddressDao{

    QueryRunner queryRunner = new QueryRunner(DbUtils.getDateSource());
    @Override
    public List<Address> getAddress(String userId) {
        String sql = "select* from address where u_id=?";
        try {
            return queryRunner.query(sql,new BeanListHandler<>(Address.class),userId);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public int deleteAddress(int id) {
        String sql="delete from address where id=?";
        try {
            return queryRunner.update(sql,id);
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int updateAddress(Address address) {
        String sql="update  address set province=?,city=?,region=?,street=?,detailed_addr=?,phone_number=? where id=?";
        Object[] params={address.getProvince(),address.getCity(),
                address.getRegion(),address.getStreet(),address.getDetailed_addr(),
                address.getPhone_number(),address.getId()};
        try {
            return queryRunner.update(sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int addAddress(Address address) {
        String sql="insert into address(u_id,create_time,province,city,region,street,detailed_addr,phone_number) values(?,?,?,?,?,?,?,?)";
        Object[] params={address.getU_id(), DateUtils.utilToSql(address.getCreate_time()),
                address.getProvince(),address.getCity(),address.getRegion(),
                address.getStreet(),address.getDetailed_addr(),address.getPhone_number()};
        try {
            return queryRunner.update(sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }
}
